package com.baizhi.cmfz.service.impl;

import com.baizhi.cmfz.dao.ArticleDao;
import com.baizhi.cmfz.entiy.Article;
import com.baizhi.cmfz.service.ArticleService;
import com.baizhi.cmfz.service.CmfzLuceneService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ArticleServiceImpl implements ArticleService {


    private Logger logger= LoggerFactory.getLogger(ArticleService.class);
    @Autowired
    private ArticleDao dao;

    @Autowired
    private CmfzLuceneService service;



    //分页与高级检索（全文检索）
    @Override
    public Map getArticleByPage(int page, int rows, String keyword) {
        HashMap map = new HashMap();
        //如果有关键词，使用索引库
        if(keyword!=null&&keyword!=""){
            List<Article> articles = service.luceneSeleteByKeyword(keyword);
            map.put("total",articles.size());
            map.put("rows",articles);
            logger.debug("索引 ，文章数据集合"+articles);

        }else{
            //没有关键词，为第一次，直接查，并创建索引库
            //删除索引库
            boolean b = service.deleteAllIndex();
            System.out.println("创建前删除索引库"+b);
            int total = dao.getTotal();
            int start=(page-1)*rows;
            int pageSize=rows;
            List<Article> list = dao.getArticleByPage(start,pageSize);
            map.put("total", total);
            map.put("rows", list);
            logger.debug("无索引 ，文章数据集合"+list);

            //创建索引库
            boolean index = service.createIndex(list);
            System.out.println("是否成功创建索引"+index);
        }
        return map;
    }




    /**
     *重置索引
     * @return
     */
    @Override
    public Map resetIndex() {
        HashMap map = new HashMap();
        try {
            List<Article> list = dao.getArticleByPage(1,10);
            //重置
            boolean b = service.resetIndex(list);
            map.put("isResetIndex",true);
            logger.debug("重置索引");
        } catch (Exception e) {
            map.put("isResetIndex",false);
            e.printStackTrace();
        }
        return map;
    }


    @Override
    public void add(Article article) {
        dao.insert(article);
    }

    @Override
    public void update(Article article) {
        dao.update(article);
    }
}
